# -*- coding:utf-8 -*-

__author__='zhaoxp'

def normalize(numbers):
    total=sum(numbers)
    result=[]
    for value in numbers:
        percent=100*value/total
        result.append(percent)
    return result

def read_visits(data_path):
    with open(data_path) as f:
        for line in f:
            yield int(line)

def normalize_copy(numbers):
    numbers=list(numbers)
    total=sum(numbers)
    result=[]
    for value in numbers:
        percent=100*value/total
        result.append(percent)
    return result

def normalize_func(get_iter):
    total=sum(get_iter())
    result=[]
    for value in get_iter():
        percent=100*value/total
        result.append(percent)
    return result

class ReadVisits(object):
    def __init__(self,data_path):
        self.data_path=data_path
    
    def __iter__(self):
        print('ReadVisits.__iter__')
        with open(self.data_path) as f:
            for line in f:
                yield int(line)

def normalize_defensive(numbers):
    if iter(numbers) is iter(numbers):
        raise TypeError('Must supply a container')
    total=sum(numbers)
    result=[]
    for value in numbers:
        percent=100*value/total
        result.append(percent)
    return result

if __name__=='__main__':
    print('show example about how to use list as arguemnt')
    print('calculate percent of every number in a list')
    l=[34,28,54,62,13,88,12]
    print('list is:',l)
    print('percnet:',normalize(l))
    print('')
    
    print('----------new data----------')
    data_path='d:\\temp\\py\\num.txt'
    '''
73
24
58
91
102
33
48
82
    '''
    it=read_visits(data_path)
    print('usage iterator:')
    print('iter per:',normalize(it))
    print('show result of list(xx)')
    it=read_visits(data_path)
    print('list first ',list(it))
    print('list second',list(it))
    print('')
    
    print('usage list copy')
    it=read_visits(data_path)
    print('copy per 1',normalize_copy(it))
    print('copy per 2',normalize_copy(it))
    print('')
    
    print('use iter func')
    print('iter func 1',normalize_func(lambda:read_visits(data_path)))
    print('iter func 2',normalize_func(lambda:read_visits(data_path)))
    print('')
    
    print('usge iter class')
    rv=ReadVisits(data_path)
    print('iter class 1',normalize(rv))
    for value in rv:
        pass
    for value in rv:
        pass
    print('')
    
    print('iter ...')
    visits=[14,23,54]
    print('list:',visits)
    print('iter ',normalize_defensive(visits))
    visits=ReadVisits(data_path)
    print('visits is',visits)
    print('iter ',normalize_defensive(visits))
    
    it=iter(visits)
    print('iter ',normalize_defensive(it))
    
    